package com.duapk.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.duapk.common.Result;
import com.duapk.common.SearchResult;
import com.duapk.web.Constants;
import com.duapk.web.conf.SystemConfig;
import com.duapk.web.log.LogManager;
import com.duapk.web.util.HttpUtils;
import com.duapk.web.util.JSONUtils;

/**
 * 搜索入口
 * 
 * @author yangfeng
 * 
 */
public class SearchServlet extends HttpServlet {

	// 日志对象
	private static Logger logger = LoggerFactory.getLogger(SearchServlet.class);

	private static final long serialVersionUID = 3301400331735599048L;

	// 首页地址
	private static final String HOME_PAGE = "/index.jsp";
	private static final String M_HOME_PAGE = "/index_m.jsp";

	// 搜索结果页面
	private static final String RESULT_PAGE = "/WEB-INF/jsp/result.jsp";
	private static final String M_RESULT_PAGE = "/WEB-INF/jsp/result_m.jsp";

	// 数据包装key
	private static final String RESULT_KEY = "result";

	private static final String KEY_WORD_KEY = "q";

	private static final String PAGE_ID_KEY = "p";

	private static final String PAGE_SIZE_KEY = "s";
	
	private static final String M_TOKEN_KEY = "m";
	
	private static final String CLIENT_WEB = "web";
	
	private static final String CLIENT_WAP = "wap";
	
	private static final String TYPE_KEY  = "t";

	private static final String searchEngineUrl = SystemConfig
			.getConfigString("search.engine.url");

	private static final int pageSize = SystemConfig
			.getConfigInt("search.web.pagesize");

	/**
	 * 注意中文问题:需要在server.xml 的 Connector 中增加 URIEncoding="gbk"
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doAction(request, response);
	}

	/**
	 * 处理Post请求
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding(HttpUtils.UTF_HTTP_ENCODING);
		doAction(request, response);
	}
	
	private void doAction(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String mobile = request.getParameter(M_TOKEN_KEY);
		String homePage = HOME_PAGE;
		String resultPage = RESULT_PAGE;
		String client = CLIENT_WEB;
		String type = request.getParameter(TYPE_KEY);
		if(mobile!=null){
			homePage = M_HOME_PAGE;
			resultPage = M_RESULT_PAGE;
			client = CLIENT_WAP;
			//处理WAP分类
		}
		if("null".equals(type)){
			type = null;
		}
		
		String keyword = request.getParameter(KEY_WORD_KEY);
		if (keyword == null || keyword.trim().length() == 0) {
			request.getRequestDispatcher(homePage).forward(request, response);
			return;
		}
		int pageID = 1;
		String pid = request.getParameter(PAGE_ID_KEY);
		if (pid != null) {
			try {
				pageID = Integer.parseInt(pid);
			} catch (Exception e) {
			}
		}
		SearchResult searchResult = search(keyword, pageID, type);
		if (searchResult == null) {
			// 记录搜索访问日志
			LogManager.searchLog(client, keyword,type, pageID, 0, request.getRemoteAddr(),
					request.getHeader(Constants.User_Agent));
			searchResult = new SearchResult();
		} else {
			List<Result> list = searchResult.getResultList();
			for(Result result:list){
				String url = result.getDownloadUrl();
				//url = EncryptorUtils.getEncryptionString(url);
				url = java.net.URLEncoder.encode(url,HttpUtils.UTF_HTTP_ENCODING);
				
				String detailUrl = result.getDetailUrl();
				detailUrl = java.net.URLEncoder.encode(detailUrl,HttpUtils.UTF_HTTP_ENCODING);
				
				String title = result.getTitle();
				//title = EncryptorUtils.getEncryptionString(title);
				title = java.net.URLEncoder.encode(title,HttpUtils.UTF_HTTP_ENCODING);
				result.setDownloadUrl("d?u="+url+"&n="+title);
				result.setDetailUrl(detailUrl);
			}
			// 记录搜索访问日志
			LogManager.searchLog(client,keyword, type,pageID, searchResult.getCurrentItem(),
					request.getRemoteHost(), request.getHeader(Constants.User_Agent));
		}
		searchResult.setKeyword(keyword);
		searchResult.setPageID(pageID);
		request.setAttribute(RESULT_KEY, searchResult);
		if(type!=null){
			request.setAttribute(TYPE_KEY, type);
		}
		request.getRequestDispatcher(resultPage).forward(request, response);
	}

	/**
	 * 获取搜索结果
	 * 
	 * @param keyword
	 * @param pageID
	 * @return
	 */
	private SearchResult search(String keyword, int pageID ,String type) {
		StringBuilder postBody = new StringBuilder();
		postBody.append(KEY_WORD_KEY).append('=').append(keyword).append('&')
				.append(PAGE_ID_KEY).append('=').append(pageID).append('&')
				.append(PAGE_SIZE_KEY).append('=').append(pageSize);
				if(type!=null){
					postBody.append('&').append(TYPE_KEY).append('=').append(type);
				}
		String content = HttpUtils.sentPost(searchEngineUrl,
				postBody.toString());
		SearchResult result = null;
		try {
			result = JSONUtils.fromJson(content, SearchResult.class);
		} catch (Exception e) {
			logger.error("Get Search Result Error! keyword={}", keyword, e);
		}
		return result;
	}
}
